<?php

class BooksController extends CController
{
    /**
     * 
     * @var array
     */
    public $menu = array();

    /**
     * 
     * @var string
     */
    public $layout='//layouts/column2';
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	public function init(){
		if(isset($_GET['lang'])){
			Yii::app()->user->setState('lang',$_GET['lang']);
		}
		if(!isset(Yii::app()->user->lang)){
			Yii::app()->user->setState('lang','english');
		}
		if(Yii::app()->user->lang != 'english'){
			Yii::app()->name = 'PHP5框架Yii1.1敏捷Web开发指南';
			Yii::app()->user->setState('lang','simpleChinese');
		}
	}
	public function actionPage()
	{
		echo $this->renderPartial('pages/'.$_GET['view']);
		Yii::app()->end();
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=new Contents;
		$booksId = intval($_GET['booksId']);

		// Uncomment the following line if AJAX validation is needed
		//$this->performAjaxValidation($model);
		if(isset($_POST['Contents']))
		{
			$model->attributes=$_POST['Contents'];
			if($model->save())
			{
				$_GET['booksId'] = $_POST['Contents']['books_id'];
				return $this->actionTest();
			}
		}
		echo $this->renderPartial('_form', array('model'=>$model,'booksId'=>$booksId));
		Yii::app()->end();
	}
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Books');
        $model = Books::model()->findAll();
        if(Yii::app()->user->lang != 'english'){
        	$id = 'directory_cn';
        }else{
        	$id = 'directory';
        }
        $data = Yii::app()->cache->get($id);
        if (!$data){
            $data = $this->getChildrenByParent(0);
            Yii::app()->cache->set($id, $data, 600); //缓存10分钟
        }
        $data = $this->getChildrenByParent(0);
        $this->menu = $data;
		$this->render('index',array(
            'menu'=>$data,
		));
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=Books::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='books-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('/error', $error);
	    }
	}
	/**
	 * 查看章节内容，如果传递来的两个参数booksId,contentsId。
	 * booksId为空，默认为books第一条记录
	 * contentId为空，默认为contents第一条记录
	 */
	public function actionTest()
	{
		$booksId = isset($_GET['booksId']) ? intval($_GET['booksId']) : '';
		$contentsId = isset($_GET['contentsId']) ? intval($_GET['contentsId']) : '';
		if(empty($booksId))
		{
			$booksId = Books::model()->find()->id;
		}
		if(empty($contentsId))
		{
			$criteria=new CDbCriteria(array(
				'condition'=>'books_id='.$booksId,
				'order'=>'create_time DESC',
			));
			$model = Contents::model()->find($criteria);
		}else{
			$model = Contents::model()->findByPk($contentsId);
			$booksId = $model->books_id;
		}
		if($model)
        {
            $data = array('content' => $model->content, 'id' => $model->books_id, 'history' => $this->showContentHistory($booksId) );
            if (isset($_GET['ajax']) && $_GET['ajax'] ==true) {
		        $this->renderPartial('test',$data);
            }else{
		        $this->renderPartial('test',$data);
            }
		}else
		{
			echo '错误请求';
			//临时创建：点击不存在时创建一条记录
//			$model=new Contents;
//			$model->books_id = $booksId;
//			$model->content = "此处是原文英语，暂空，待补充";
//			$model->save();
			
		}
		 Yii::app()->end();
	}
	/**
	 *  根据传递的$booksId，获取修改历史
	 */
	private function showContentHistory($booksId)
	{
		if(!$booksId)
		{
			$booksId = Books::model()->find()->id;
		}
		$criteria=new CDbCriteria(array(
			'select'=>'id,create_time',
			'condition'=>'books_id='.$booksId,
			'order'=>'create_time DESC',
		));
        $model = Contents::model()->findAll($criteria);
        $temp = '';
		if($model)
		{
			foreach ($model as $v) {
				$temp .= "<a href=\"#\" onclick=\"viewContents('".$v->id."');return false;\">".date("Y-m-d H:i:s",$v->create_time)."</a><br />";
			}
		}else{
			$temp = '无相关数据';
        }
        return $temp;
    }

    private function getChildrenByParent($pid)
    {
        $pid = empty($pid) ? 0 : intval($pid);
        $data = Books::model()->findAll('rank=:pid',array(':pid'=>$pid));
        $list = array();
        if ($data){
            foreach($data as $item) {
                $temp = array(
                    'label' => (Yii::app()->user->lang!='english')?$item->cntitle:$item->title,
                    'url'   => array('books/test', 'booksId' => $item->id ),
                );
                $children = $this->getChildrenByParent($item->id);
                if ($children){
                    $temp['items'] = $children;
                };
            
                $list[] = $temp;
            }
        }
        return $list;
    }
    /**
     * 更新目录功能
     * 从文本文件中读取记录
     * 读取books中文标题字段 
     * 循环赋值每一行对应表中一条记录的中文字段
     */
//    public function actionUpdatecn(){
//		$file = file("/home/loong/tmp.txt");
//		$i=1;
//		$txt = array();
//		foreach($file as &$line){
//			//echo $i++;echo $line.'<br />';
//			$txt[$i++] = $line;
//		}
//    	$data = Books::model()->findAll();
//    	$i=1;$j=1;
//    	foreach($data as $v){
//    		$v->cntitle = $txt[$i++];
//    		echo $j++;echo $v->cntitle.'----'.$v->title .'<br />';
//    		$v->save();
//    	}
//    }
}
